#!/bin/sh
# Build SD card image

BOARD_ID="${1}" # For example "bananapi"
CHIP_ID="${2}" # For example "allwinner-a10"
DEFCONFIG="${3}" # For example "Bananapi_defconfig"
TUPLE="${4}" # For example "arm-linux-gnueabihf"

set -ex

# Create fresh empty directory
TMP=$(mktemp -d -p "${PWD}" tmp-XXXXXX)
trap 'rm -rf "${TMP}"' EXIT INT TERM
cd "${TMP}"

build-image tmp.img

case "${CHIP_ID}" in
allwinner*)
    build-boot-sunxi "${BOARD_ID}" "${CHIP_ID}" "${DEFCONFIG}" "${TUPLE}"
    ;;
bcm2836|bcm2837|bcm2711)
    build-boot-rpi "${BOARD_ID}" "${CHIP_ID}" "${DEFCONFIG}" "${TUPLE}"
    ;;
rk*)
    build-boot-rk "${BOARD_ID}" "${CHIP_ID}" "${DEFCONFIG}" "${TUPLE}"
    ;;
meson-*)
    build-boot-meson "${BOARD_ID}" "${CHIP_ID}" "${DEFCONFIG}" "${TUPLE}"
    ;;
qemu*)
    build-boot-qemu "${BOARD_ID}" "${CHIP_ID}" "${DEFCONFIG}" "${TUPLE}"
    ;;
*)
    echo "Unknown CHIP_ID \"${CHIP_ID}\""
    exit 1
    ;;
esac

truncate -s 32M tmp.img
pigz tmp.img

mkdir -p "${ARTIFACTS_DIR:-/artifacts}"
cp -v versions.csv "${ARTIFACTS_DIR:-/artifacts}/boot-${BOARD_ID}.bin.gz.versions.csv"
cp -v tmp.img.gz "${ARTIFACTS_DIR:-/artifacts}/boot-${BOARD_ID}.bin.gz"
